package com.willcode.demo.orm.hibernate.dao.impl;

import cn.hutool.json.JSONUtil;
import com.willcode.demo.orm.hibernate.entity.User;
import org.hibernate.SQLQuery;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;

/**
 * @author Will
 */
@Repository
public class IUserMapperImpl {

    @PersistenceContext
    private EntityManager entityManager;

    public User find4Link(String id) {

        /*// JPA 推荐写法
        User user = entityManager.find(User.class, "SELECT user FROM User user where id = :id");*/

        String sql = "SELECT A.*,B.relation FROM user A LEFT JOIN userrelation B ON A.id = B.parentid WHERE A.ID = :id";
        Query query = entityManager.createNativeQuery(sql);
        query.setParameter("id", id);

        /*// 已废弃写法，有些环境不支持新写法
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);*/

        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List resultList = query.getResultList();

        String s = JSONUtil.toJsonStr(resultList);
        System.out.println(s);

        return null;
    }


}
